//
//  MyViewController.m
//  News
//
//  Created by 宋浩文的pro on 16/5/22.
//  Copyright © 2016年 songhaowen. All rights reserved.
//

#import "MyViewController.h"
#import "UIImageView+WebCache.h"
#import "MBProgressHUD.h"
#import "CommonTool.h"
#import "MyAttentionViewController.h"
#import "MainTabBarController.h"

@interface MyViewController ()<UIImagePickerControllerDelegate, UINavigationControllerDelegate, UITableViewDelegate, UITableViewDataSource>


@property (weak, nonatomic) IBOutlet UIImageView *headerImageView;

@property (weak, nonatomic) IBOutlet UILabel *nameLabel;


@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (nonatomic, copy) NSString *imagePath;

/** tableView的数据源 */
@property (nonatomic, strong) NSArray *selectListArray;

@end



@implementation MyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    [self initUI];
    
    self.view.backgroundColor = RGBCOLOR(239, 239, 244, 1);
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    [self.navigationController setNavigationBarHidden:YES animated:animated];

    [self readCache];
}

- (void)initUI
{
    _headerImageView.layer.cornerRadius = 40;
    _headerImageView.layer.masksToBounds = YES;
    _headerImageView.userInteractionEnabled = YES;
    
    UITapGestureRecognizer *tapGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(headerUpload)];
    [_headerImageView addGestureRecognizer:tapGR];
    
    
    
    
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.bounces = NO;
}

#pragma mark - UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.selectListArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:nil];
   
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    cell.textLabel.text = self.selectListArray[indexPath.row];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        MyAttentionViewController *attentionVC = [[MyAttentionViewController alloc] init];
        
        [self.navigationController pushViewController:attentionVC animated:YES];
        
    } else if (indexPath.row == 1) {
     
        
    } else if (indexPath.row == 2) {
        
    } else if(indexPath.row == 3){
        
     
        
        
    } else {
        [BmobUser logout];
        [CommonTool showSuccess:@"退出成功！"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            [UIApplication sharedApplication].keyWindow.rootViewController = [[MainTabBarController alloc] init];
        });
    }
    // 取消选中效果
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}



- (void)readCache
{
    BmobUser *user = [BmobUser getCurrentUser];
    UIImage *iconImage = [[SDImageCache sharedImageCache] imageFromDiskCacheForKey:[NSString stringWithFormat:@"iconImage_%@", user.objectId]];
    if (iconImage) {
        [self.headerImageView setImage:iconImage];
    } else {
        
        // 从网络上请求
        BmobQuery   *bquery = [BmobQuery queryWithClassName:@"_User"];
        
        [bquery getObjectInBackgroundWithId:user.objectId block:^(BmobObject *object,NSError *error){
            if (error){
                //进行错误处理
                [CommonTool showError:@"网络无连接"];
            }else{
                if (object) {
                    
                    NSString *username = [object objectForKey:@"username"];
                    self.nameLabel.text = username;
                    
                    BmobFile *bFile = (BmobFile*)[object objectForKey:@"avatar"];
                    [self.headerImageView sd_setImageWithURL:[NSURL URLWithString:bFile.url] placeholderImage:[UIImage imageNamed:@"user_icon_default"]];
                    
                    // 对图片做缓存
                    [[SDImageCache sharedImageCache] storeImage:self.headerImageView.image forKey:[NSString stringWithFormat:@"iconImage_%@", user.objectId] toDisk:YES];
                    
                    
                }
            }
        }];
        

        
    }
    
    _nameLabel.text = user.username;
    
}

- (void)headerUpload
{
    NSUInteger __block sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"更换头像" preferredStyle:UIAlertControllerStyleActionSheet];
    // 调用相册
    UIAlertAction *action_photoLibrary = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
        // 跳转到相机或相册页面
        UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
        imagePickerController.delegate = self;
        imagePickerController.allowsEditing = YES;
        imagePickerController.sourceType = sourceType;
        [self presentViewController:imagePickerController animated:YES completion:nil];
    }];
    // 调用相机
    UIAlertAction *action_camera = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            sourceType = UIImagePickerControllerSourceTypeCamera;
            // 跳转到相机或相册页面
            UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
            imagePickerController.delegate = self;
            imagePickerController.allowsEditing = YES;
            imagePickerController.sourceType = sourceType;
            [self presentViewController:imagePickerController animated:YES completion:nil];
            NSLog(@"拍照");
        } else {
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:nil preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *action_error = [UIAlertAction actionWithTitle:@"相机不可用" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
            }];
            [alertController addAction:action_error];
            [self presentViewController:alertController animated:YES completion:nil];
        }
    }];
    UIAlertAction *action_cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    // 将action加入alertController里
    [alertController addAction:action_camera];
    [alertController addAction:action_photoLibrary];
    [alertController addAction:action_cancel];
    
    
    
    [self presentViewController:alertController animated:YES completion:^{}];
}

/** 选择图片，还要上传到后台 */
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    
    
    UIImage *image = info[UIImagePickerControllerEditedImage];
    _headerImageView.image = image;
    
    
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *imagePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"headIcon.png"]];
    self.imagePath = imagePath;
    [UIImagePNGRepresentation(info[UIImagePickerControllerEditedImage]) writeToFile:imagePath atomically:YES];
    
    BmobUser *bUser = [BmobUser getCurrentUser];
    
    // 对图片做缓存
    [[SDImageCache sharedImageCache] storeImage:image forKey:[NSString stringWithFormat:@"iconImage_%@", bUser.objectId] toDisk:YES];
    
    
    [picker dismissViewControllerAnimated:YES completion:^{}];
    
    
    // 上传图片
    MBProgressHUD *hud_save = [MBProgressHUD showHUDAddedTo:Window animated:YES];
    hud_save.labelText = @"上传头像中";
    
    
    BmobUser *user = [BmobUser getCurrentUser];
    BmobQuery *bquery = [BmobQuery queryWithClassName:@"_User"];
    [bquery getObjectInBackgroundWithId:user.objectId block:^(BmobObject *object, NSError *error) {
        
        BmobFile *bmobFile = [[BmobFile alloc] initWithClassName:@"_User" withFilePath:self.imagePath];
        //异步更新数据
        [bmobFile saveInBackground:^(BOOL isSuccessful, NSError *error) {
            [hud_save hide:YES];
            if (isSuccessful) {
                [CommonTool showSuccess:@"保存成功"];
                [object setObject:bmobFile forKey:@"avatar"];
                [object updateInBackground];
            } else {
                [CommonTool showError:@"上传失败"];
            }
        }];
    }];
    

    
}


#pragma mark - 懒加载
- (NSArray *)selectListArray
{
    if (_selectListArray == nil) {
        
        // 八字先生身份
        _selectListArray = @[@"我的收藏", @"我的评论", @"编辑资料", @"设置",@"退出登录"];
   
    }
    return _selectListArray;
}

@end
